package com.dominator.utils.pay;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.dominator.utils.system.Constants;
import com.dominator.utils.system.SeemseUtil;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.system.PropertiesLoader;
import org.dom4j.Element;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

import net.sf.json.JSONObject;

public class AliWeixinSignCheck {
	public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");
	/**支付宝订单CODE返回为9000时候**/
	public static boolean  AL_signCheck_OK(String result ){
		System.out.println(result);
		JSONObject  jasonObject = JSONObject.fromObject(result);
	
		String content = jasonObject.get("alipay_trade_query_response")+"";
		String sign = jasonObject.get("sign")+"";
		boolean type = true;
		//进行验签
		try {
			type = AlipaySignature.rsaCheckContent(content, sign, Constants.AL_ALIPAY_PUBLIC_KEY_SRA, "utf-8");
		} catch (AlipayApiException e) {
			System.out.println("=====================支付验签===============================");
			System.out.println("=====================支付验签===============================");
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return type;
	}
	
	/**支付宝订单CODE返回非9000时候**/
	/**8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
		4000	订单支付失败
		5000	重复请求
		6001	用户中途取消
		6002	网络连接出错
		6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
		其它	其它支付错误**/
	public static ApiMessage AL_signCheck_NO(String code){
		ApiMessage msg = new ApiMessage();
		msg.setCode(Constants.REQ_TRADE_ERROR);
		switch (code) {
		case "8000":
			msg.setMessage("正在处理中，支付结果未知");
			break;
		case "4000":
			msg.setMessage("订单支付失败");		
			break;
		case "5000":
			msg.setMessage("重复请求");	
			break;
		case "6001":
			msg.setMessage("用户中途取消");	
			break;
		case "6002":
			msg.setMessage("网络连接出错");	
			break;
		case "6004":
			msg.setMessage("支付结果未知");	
			break;
		default:
			msg.setMessage("支付异常");	
			break;
		}
		return msg;
	}
/*	*//**支付宝验签**//*
	public static String AL_sign_check_sign(){
		ALI_check_sign
	}*/
	/**微信验签**/
	public static Map<String,Object> WX_sign_check_sign(String transaction_id,String out_trade_no){
		SortedMap<String, Object> signMap = new TreeMap<String, Object>();
		signMap.put("appid", propertiesLoader.getProperty("wx_public_appid"));
		signMap.put("mch_id",  propertiesLoader.getProperty("wx_public_MchId"));
		//作为微信订单号或者商户订单号的标识符（0：商户订单号		1：微信订单号）
		int type = 0;
		if(transaction_id!=null){
			type = 1; 
			signMap.put("transaction_id", transaction_id);
		}
		if(transaction_id==null&&out_trade_no!=null){
			signMap.put("out_trade_no", out_trade_no);
		}
		signMap.put("nonce_str", SeemseUtil.randoms());
		String sign = WxPaySign.createSign(signMap,null);
		signMap.put("sign", sign);
		return WX_signCheck(signMap,type);
	}
	/**进行订单查询**/
	public static Map<String,Object> WX_signCheck(SortedMap<String, Object> signMap ,int type){
		Map<String,String>map = new HashMap<String,String>();
		map.put("appid", propertiesLoader.getProperty("wx_public_appid"));
		map.put("mch_id", propertiesLoader.getProperty("wx_public_MchId"));
		map.put("nonce_str", signMap.get("nonce_str")+"");
		if(type==1){
			map.put("transaction_id", signMap.get("transaction_id")+"");
		}
		if(type==0){
			map.put("out_trade_no", signMap.get("out_trade_no")+"");
		}
		map.put("sign",signMap.get("sign")+"");
		String xml = SeemseUtil.createXml(map);
		System.out.println(xml);
		String returnXml = HttpKit.post(Constants.WX_OrderUrl, xml);
		System.out.println(returnXml);
		Element root = XmlParser.doParse(returnXml);
		return WX_return_analysis(root,returnXml);
	}
	/**微信返回查询结果解析**/
	public static Map<String,Object> WX_return_analysis(Element root,String returnXml){
		Map<String,Object>respMap = new HashMap<String,Object>();
		ApiMessage msg = new ApiMessage();
		String return_code = root.elementTextTrim("return_code") ;
		String result_code = root.elementTextTrim("result_code") ;
		if(return_code.equals("SUCCESS")&&result_code.equals("SUCCESS")){
			String trade_state = root.elementTextTrim("trade_state");
			//判断订单是否成功
			if(trade_state.equals("SUCCESS")){
				msg.setCode(Constants.REQ_SUCCESS);
				msg.setMessage("交易成功");
				respMap.put("total_fee", root.elementTextTrim("total_fee"));
				respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
				respMap.put("msg",msg);
			}else{
				/**	REFUND—转入退款 	NOTPAY—未支付	 CLOSED—已关闭	 REVOKED—已撤销（刷卡支付）USERPAYING--用户支付中
				PAYERROR--支付失败(其他原因，如银行返回失败)**/
				switch (trade_state) {
				case "REFUND":
					msg.setMessage("转入退款");
					break;
				case "NOTPAY":
					msg.setMessage("未支付");
					break;
				case "CLOSED":
					msg.setMessage("已关闭");
					break;
				case "REVOKED":
					msg.setMessage("已撤销");
					break;
				case "USERPAYING":
					msg.setMessage("用户支付中");
					break;
				case "PAYERROR":
					msg.setMessage("支付失败");
					break;
				}
				msg.setCode(Constants.REQ_TRADE_ERROR);
				respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
				respMap.put("msg",msg);
			}
		}else{
			msg.setCode(Constants.REQ_TRADE_ERROR);
			msg.setCode(root.elementTextTrim("err_code"));
			respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
			respMap.put("msg",msg);
		}
		respMap.put("returnXml", returnXml);
		return respMap;
	}
	
	/**微信验签**/
	public static Map<String,Object> WX_sign_check_sign_public(String transaction_id,String out_trade_no){
		SortedMap<String, Object> signMap = new TreeMap<String, Object>();
		signMap.put("appid",propertiesLoader.getProperty("wx_public_appid"));
		signMap.put("mch_id", propertiesLoader.getProperty("wx_public_MchId"));
		//作为微信订单号或者商户订单号的标识符（0：商户订单号		1：微信订单号）
		int type = 0;
		if(transaction_id!=null){
			type = 1; 
			signMap.put("transaction_id", transaction_id);
		}
		if(transaction_id==null&&out_trade_no!=null){
			signMap.put("out_trade_no", out_trade_no);
		}
		signMap.put("nonce_str", SeemseUtil.randoms());
		String sign = WxPaySign.createSign(signMap,propertiesLoader.getProperty("wx_public_key"));
		signMap.put("sign", sign);
		return WX_signCheck_public(signMap,type);
	}
	/**进行订单查询**/
	public static Map<String,Object> WX_signCheck_public(SortedMap<String, Object> signMap ,int type){
		Map<String,String>map = new HashMap<String,String>();
		map.put("appid",propertiesLoader.getProperty("wx_public_appid"));
		map.put("mch_id", propertiesLoader.getProperty("wx_public_MchId"));
		map.put("nonce_str", signMap.get("nonce_str")+"");
		if(type==1){
			map.put("transaction_id", signMap.get("transaction_id")+"");
		}
		if(type==0){
			map.put("out_trade_no", signMap.get("out_trade_no")+"");
		}
		map.put("sign",signMap.get("sign")+"");
		String xml = SeemseUtil.createXml(map);
		System.out.println(xml);
		String returnXml = HttpKit.post(Constants.WX_OrderUrl, xml);
		System.out.println(returnXml);
		Element root = XmlParser.doParse(returnXml);
		return WX_return_analysis_public(root,returnXml);
	}
	/**微信返回查询结果解析**/
	public static Map<String,Object> WX_return_analysis_public(Element root,String returnXml){
		Map<String,Object>respMap = new HashMap<String,Object>();
		ApiMessage msg = new ApiMessage();
		String return_code = root.elementTextTrim("return_code") ;
		String result_code = root.elementTextTrim("result_code") ;
		if(return_code.equals("SUCCESS")&&result_code.equals("SUCCESS")){
			String trade_state = root.elementTextTrim("trade_state");
			//判断订单是否成功
			if(trade_state.equals("SUCCESS")){
				msg.setCode(Constants.REQ_SUCCESS);
				msg.setMessage("交易成功");
				respMap.put("total_fee", root.elementTextTrim("total_fee"));
				respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
				respMap.put("msg",msg);
			}else{
				/**	REFUND—转入退款 	NOTPAY—未支付	 CLOSED—已关闭	 REVOKED—已撤销（刷卡支付）USERPAYING--用户支付中
				PAYERROR--支付失败(其他原因，如银行返回失败)**/
				switch (trade_state) {
				case "REFUND":
					msg.setMessage("转入退款");
					break;
				case "NOTPAY":
					msg.setMessage("未支付");
					break;
				case "CLOSED":
					msg.setMessage("已关闭");
					break;
				case "REVOKED":
					msg.setMessage("已撤销");
					break;
				case "USERPAYING":
					msg.setMessage("用户支付中");
					break;
				case "PAYERROR":
					msg.setMessage("支付失败");
					break;
				}
				msg.setCode(Constants.REQ_TRADE_ERROR);
				respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
				respMap.put("msg",msg);
			}
		}else{
			msg.setCode(Constants.REQ_TRADE_ERROR);
			respMap.put("out_trade_no",root.elementTextTrim("out_trade_no") );
			respMap.put("msg",msg);
		}
		respMap.put("returnXml", returnXml);
		return respMap;
	}
}
